package com.yanqu.road.server.manger.activity.flowerstudy;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.flowerstudy.config.*;
import com.yanqu.road.entity.activity.flowerstudy.data.FlowerStudyUserWarReport;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.logic.bussiness.activity.FlowerStudyBusiness;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.pb.activity.FlowerStudyProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.flowerstudy.FlowerStudyModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.manger.union.UnionActivityMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.string.StringUtils;


import java.math.BigInteger;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class FlowerStudyMgr extends TempMgr {

    private static FlowerStudyConfig config;

    private static ActivityInfo activityInfo;

    private static RandomHelper randomHelper = new RandomHelper();
    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static void reloadActivityData() {
        getLogger().info("reload Flower Study Activity start");

        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.FlowerStudy.getValue());
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no Flower Study Activity in show time");
            config = null;
            activityInfo = null;
            return;
        }
        activityInfo = openActivityInfoList.get(0);
        //活动配置
        int activityId = activityInfo.getActivityId();
        Map<Integer, FlowerStudyExamConfig> tmpFlowerStudyExamConfigMap = FlowerStudyBusiness.getFlowerStudyExamConfigMap(activityId);
        Map<Integer, FlowerStudyVisitConfig> tmpFlowerStudyVisitConfigMap = FlowerStudyBusiness.getFlowerStudyVisitConfigMap(activityId);
        Map<Integer, FlowerStudyPoemConfig> tmpFlowerStudyPoemConfigMap = FlowerStudyBusiness.getFlowerStudyPoemConfigMap(activityId);
        List<FlowerStudyTitleConfig> tmpFlowerStudyTitleConfigList = FlowerStudyBusiness.getFlowerStudyTitleConfigList(activityId);
        Map<Integer, FlowerStudyExamQuestionConfig> studyExamQuestionConfigMap = FlowerStudyBusiness.getFlowerStudyExamQuestionConfigMap(activityId);
        Map<Integer, Map<Integer, FlowerStudySessionRewardConfig>> tmpFlowerStudySessionRewardConfigMap = FlowerStudyBusiness.getFlowerStudySessionRewardConfigMap(activityId);
        //其他
        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(activityId);

        config = new FlowerStudyConfig(activityInfo,tmpFlowerStudyVisitConfigMap,tmpFlowerStudyPoemConfigMap,tmpFlowerStudyExamConfigMap,tmpFlowerStudyTitleConfigList,studyExamQuestionConfigMap,tmpFlowerStudySessionRewardConfigMap,activityConfigMap);

        getLogger().info("reload FlowerStudy end, activityId {}.", activityInfo.getActivityId());
        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            FlowerStudyModule module = player.getModule(FlowerStudyModule.class);
            module.syncConfig();
            module.syncUserData();
            module.checkPoemRefresh();
            module.checkVisitRefresh();
        }

    }

    public static void addReport(long userId,FlowerStudyProto.FlowerStudyExamRoomDataSync msg){
        FlowerStudyUserWarReport report = new FlowerStudyUserWarReport();
        int activityId = FlowerStudyMgr.getActivityInfo().getActivityId();
        report.setActivityId(activityId);
        report.setUserId(userId);
        report.setRoomId(msg.getRoomData().getRoomId());
        report.setRoomType(msg.getRoomData().getRoomType());
        report.setReward("");
        if (msg.hasReward()){
            report.setReward(msg.getReward());
        }
        report.setSettlementTime(System.currentTimeMillis());

        List<FlowerStudyProto.FlowerStudyExamUserBattleData> userBattleDataList = msg.getRoomData().getUserBattleDataList();
        FlowerStudyProto.FlowerStudyExamUserBattleData myBattleData = null;
        for (FlowerStudyProto.FlowerStudyExamUserBattleData userBattleData: userBattleDataList){
            if (userBattleData.getUserId() == userId){
                myBattleData = userBattleData;
            }
        }
        if (myBattleData == null){
            List<FlowerStudyUserWarReport> dataList = new ArrayList<>();
            dataList.add(report);
            FlowerStudyBusiness.addFlowerStudyUserWarReportList(dataList);
            return;
        }

        int myRank = 1;
        for (FlowerStudyProto.FlowerStudyExamUserBattleData userBattleData: userBattleDataList){
            if (userBattleData.getUserId() != userId){
                if (userBattleData.getScoreThisExam() > myBattleData.getScoreThisExam()){
                    myRank++;
                }if (userBattleData.getScoreThisExam() == myBattleData.getScoreThisExam()){
                    if (userBattleData.getTotalUseTime() <= myBattleData.getTotalUseTime()){
                        myRank++;
                    }
                }
            }
        }
        report.setRank(myRank);
        report.setScore(myBattleData.getScoreThisExam());
        report.setAnswerTime(myBattleData.getTotalUseTime());

        List<FlowerStudyUserWarReport> dataList = new ArrayList<>();
        dataList.add(report);
        FlowerStudyBusiness.addFlowerStudyUserWarReportList(dataList);
        return;

    }

    public static FlowerStudyProto.FlowerStudyConfigSync.Builder getFlowerStudyConfigMsg(String language){
        if (activityInfo == null){
            return null;
        }
        if (config == null){
            return null;
        }
        FlowerStudyProto.FlowerStudyConfigSync.Builder builder = FlowerStudyProto.FlowerStudyConfigSync.newBuilder();
        for (FlowerStudyVisitConfig visitConfig: config.getVisitConfigMap().values()){
            FlowerStudyProto.FlowerStudyVisitConfig.Builder visitConfigMsg =FlowerStudyProto.FlowerStudyVisitConfig.newBuilder();
            visitConfigMsg.setId(visitConfig.getId());
            visitConfigMsg.setDesc(ServerLanguageMgr.getContent(visitConfig.getDesc(),language));
            visitConfigMsg.setReward(visitConfig.getReward());
            builder.addVisitConfig(visitConfigMsg);
        }
        for (FlowerStudyPoemConfig flowerStudyPoemConfig:config.getPoemConfigMap().values()){
            FlowerStudyProto.FlowerStudyPoemConfig.Builder poemConfigMsg = FlowerStudyProto.FlowerStudyPoemConfig.newBuilder();
            poemConfigMsg.setId(flowerStudyPoemConfig.getId());
            poemConfigMsg.setDesc(ServerLanguageMgr.getContent(flowerStudyPoemConfig.getDesc(),language));
            poemConfigMsg.setExtendParam(flowerStudyPoemConfig.getExtendParam());
            builder.addPoemConfig(poemConfigMsg);
        }
        for (FlowerStudyExamConfig examConfig:config.getExamConfigMap().values()){
            FlowerStudyProto.FlowerStudyExamConfig.Builder examConfigMsg = FlowerStudyProto.FlowerStudyExamConfig.newBuilder();
            examConfigMsg.setId(examConfig.getId());
            examConfigMsg.setType(examConfig.getType());
            examConfigMsg.setName(ServerLanguageMgr.getContent(examConfig.getName(),language));
            examConfigMsg.setSession(ServerLanguageMgr.getContent(examConfig.getSession(),language));
            examConfigMsg.setStartTime(examConfig.getStartTime ());
            examConfigMsg.setEndTime(examConfig.getEndTime());
            builder.addExamConfig(examConfigMsg);
        }
        for (FlowerStudyTitleConfig titleConfig:config.getTitleConfigList()){
            FlowerStudyProto.FlowerStudyTitleConfig.Builder titleConfigMsg = FlowerStudyProto.FlowerStudyTitleConfig.newBuilder();
            titleConfigMsg.setId(titleConfig.getId());
            titleConfigMsg.setType(titleConfig.getType());
            titleConfigMsg.setRank(titleConfig.getRank());
            titleConfigMsg.setExamTypeName(ServerLanguageMgr.getContent(titleConfig.getExamTypeName(),language));
            titleConfigMsg.setName(ServerLanguageMgr.getContent(titleConfig.getName(),language));
            builder.addTitleConfig(titleConfigMsg);
        }
        for (FlowerStudyExamQuestionConfig questionConfig:config.getStudyExamQuestionConfigMap().values()){
            FlowerStudyProto.FlowerStudyExamQuestionConfig.Builder questionConfigMsg = FlowerStudyProto.FlowerStudyExamQuestionConfig.newBuilder();
            questionConfigMsg.setId(questionConfig.getId());
            questionConfigMsg.setQuestionDesc(ServerLanguageMgr.getContent(questionConfig.getQuestionDesc(),language));
            //6.4花城优化 不发答案下去了
            questionConfigMsg.setAnswer(-1);
            builder.addExamQuestionConfig(questionConfigMsg);
        }
        for (Map<Integer, FlowerStudySessionRewardConfig> map:config.getSessionRewardConfigMap().values()){
            for (FlowerStudySessionRewardConfig rewardConfig:map.values()){
                FlowerStudyProto.FlowerStudyExamRewardConfig.Builder rewardConfigMsg = FlowerStudyProto.FlowerStudyExamRewardConfig.newBuilder();
                rewardConfigMsg.setType(rewardConfig.getType());
                rewardConfigMsg.setReward(rewardConfig.getReward());
                rewardConfigMsg.setRightNum(rewardConfig.getRightNum());
                builder.addExamRewardConfig(rewardConfigMsg);
            }
        }
        return builder;
    }

    public static FlowerStudyConfig getConfig() {
        return config;
    }

    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }


    /**
     * 获取每日初始化诗书问答卷子
     * @return
     */

    public static Map<Integer,Integer> getRandomPoemMap(){
        if (config == null){
            return null;
        }
        Map<Integer, FlowerStudyPoemConfig> poemConfigMap = config.getPoemConfigMap();
        if (poemConfigMap ==null || poemConfigMap.isEmpty()){
            return null;
        }
        Map<Integer,Integer> initPoemMap = new ConcurrentHashMap<>();
        List<Integer> idList = new ArrayList<>(poemConfigMap.keySet());
        int poemQANum = config.getPoemQANum();
        if (idList.size() < poemQANum){
            getLogger().error("花城书房诗词题库数量不足,activityId = {}",activityInfo.getActivityId());
            return null;
        }
        randomHelper.shuffleList(idList);
        for (int i = 0;i<poemQANum;i++){
            initPoemMap.put(idList.get(i),0);
        }
        return initPoemMap;
    }

    /**
     * 获取随机一个名人拜访
     * @return
     */
    public static int getRandomVisitManId(){
        if (config == null){
            return 0;
        }
        Map<Integer, FlowerStudyVisitConfig> visitConfigMap = config.getVisitConfigMap();
        if (visitConfigMap == null || visitConfigMap.isEmpty()){
            return 0;
        }
        List<Integer> idList = new ArrayList<>(visitConfigMap.keySet());
        randomHelper.shuffleList(idList);
        return idList.get(0);
    }

    /**
     * 根据id获取名人拜访配置
     */
    public static FlowerStudyVisitConfig getVisitConfigById(int id) {
        if (config == null) {
            return null;
        }
        Map<Integer, FlowerStudyVisitConfig> visitConfigMap = config.getVisitConfigMap();
        if (visitConfigMap == null || visitConfigMap.isEmpty()) {
            return null;
        }
        return visitConfigMap.get(id);
    }

    /**
     * 更新离线玩家的排行榜 应该用不上
     */
    public static void updateOffLineUserRank(long userId,FlowerStudyProto.CrossFlowerStudyUserData crossUserData){
        if (crossUserData.getActivityId() != activityInfo.getActivityId()){
            return;
        }

        List<ActivityConditionInfo> activityConditionInfoList = NormalActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId());
        UserActivityConditionData localCondition = null;
        UserActivityConditionData provinceCondition = null;
        UserActivityConditionData palaceCondition = null;

        if(null != activityConditionInfoList && activityConditionInfoList.size() > 0){
            List<UserActivityConditionData> localExamConditionData = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityInfo.getActivityId(), userId, eGamePlayerEventType.FlowerStudyScoreLocalRankCondition.getValue());
            List<UserActivityConditionData> provinceExamConditionData = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityInfo.getActivityId(), userId, eGamePlayerEventType.FlowerStudyScoreProvinceRankCondition.getValue());
            List<UserActivityConditionData> palaceExamConditionData = UserActivityBussiness.getUserActivityConditionDataListByUserIdAndType(activityInfo.getActivityId(), userId, eGamePlayerEventType.FlowerStudyScorePalaceRankCondition.getValue());


            if(localExamConditionData.isEmpty() && crossUserData.getLocalScore() > 0){
                localCondition = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.valueOf(crossUserData.getLocalScore()),
                        activityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                UserActivityBussiness.addUserActivityConditionData(localCondition);
            }else {
                localCondition = localExamConditionData.get(0);
            }

            if(provinceExamConditionData.isEmpty() && crossUserData.getProvinceScore() > 0){
                provinceCondition = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.valueOf(crossUserData.getLocalScore()),
                        activityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                UserActivityBussiness.addUserActivityConditionData(provinceCondition);
            }else {
                provinceCondition = provinceExamConditionData.get(0);
            }

            if(palaceExamConditionData.isEmpty() && crossUserData.getPalaceScore() > 0){
                palaceCondition = NormalActivityMgr.initUserActivityConditionData(userId, UserMgr.getNickName(userId), BigInteger.valueOf(crossUserData.getLocalScore()),
                        activityInfo.getActivityId(), activityConditionInfoList.get(0).getConditionId(), activityConditionInfoList.get(0).getType());
                UserActivityBussiness.addUserActivityConditionData(palaceCondition);
            }else {
                palaceCondition = palaceExamConditionData.get(0);
            }
            Date now = new Date();
            if (localCondition != null && crossUserData.getLocalScore() > 0){

                if (now.before(config.getLocalExamBeginDate()) || now.after(config.getLocalExamEndDate())){
                    return;
                }
                localCondition.setValue(BigInteger.valueOf(crossUserData.getLocalScore()));
                UserActivityBussiness.updateUserActivityConditionData(localCondition);
                RankMgr.changeActivityRank(activityInfo.getActivityId(), userId, localCondition.getValue(), localCondition.getParam());
            }

            if (provinceCondition != null && crossUserData.getProvinceScore() > 0){

                if (now.before(config.getProvincialExamBeginDate()) || now.after(config.getProvincialExamEndDate())){
                    return;
                }
                provinceCondition.setValue(BigInteger.valueOf(crossUserData.getProvinceScore()));
                UserActivityBussiness.updateUserActivityConditionData(provinceCondition);
                RankMgr.changeActivityRank(activityInfo.getActivityId(), userId, provinceCondition.getValue(), provinceCondition.getParam());
            }

            if (palaceCondition != null && crossUserData.getPalaceScore() > 0){
                if (now.before(config.getPalaceExamBeginDate()) || now.after(config.getPalaceExamEndDate())){
                    return;
                }
                palaceCondition.setValue(BigInteger.valueOf(crossUserData.getPalaceScore()));
                UserActivityBussiness.updateUserActivityConditionData(palaceCondition);
                RankMgr.changeActivityRank(activityInfo.getActivityId(), userId, palaceCondition.getValue(), palaceCondition.getParam());
            }
        }

    }

    public static String getExamName(int type,String language){
        String examName = "";
        for (FlowerStudyExamConfig examConfig:config.getExamConfigMap().values()){
            if (examConfig.getType() == type){
                examName = examConfig.getName();
                break;
            }
        }
        examName = ServerLanguageMgr.getContent(examName,language);
        return examName;
    }


    //补下离线玩家的奖励
    public static void dealOfflineExamEventSync(long userId,FlowerStudyProto.FlowerStudyExamRoomDataSync msg){
        addReport(userId,msg);
        if (config == null){
            getLogger().error("FlowerStudy dealOfflineExamEventSync config is null activityId = {},userId = {}",activityInfo.getActivityId(),userId);
            return;
        }
        String reward = msg.getReward();
        if (!StringUtils.isNullOrEmpty(reward)){
            UserInfo userInfo = UserMgr.getUserInfo(userId);
            if (userInfo == null){
                getLogger().error("FlowerStudy dealOfflineExamEventSync userInfo is null activityId = {},userId = {}",activityInfo.getActivityId(),userId);
                return;
            }
            if (userInfo != null){
                long myScore = 0;
                List<FlowerStudyProto.FlowerStudyExamUserBattleData> userBattleDataList = msg.getRoomData().getUserBattleDataList();
                FlowerStudyProto.FlowerStudyExamUserBattleData myBattleData = null;
                for (FlowerStudyProto.FlowerStudyExamUserBattleData userBattleData: userBattleDataList){
                    if (userBattleData.getUserId() == userId){
                        myBattleData = userBattleData;
                    }
                }
                if (myBattleData != null){
                    myScore = myBattleData.getScoreThisExam();
                }
                String activityName = ServerLanguageMgr.getContent(activityInfo.getActivityName(), userInfo.getLanguage());
                String title = ServerLanguageMgr.getContent(config.getMailTitle(), userInfo.getLanguage());
                String examName = getExamName(msg.getRoomData().getRoomType(), userInfo.getLanguage());


                String content = StringUtils.format(ServerLanguageMgr.getContent(config.getMailContent(), userInfo.getLanguage()),activityName,examName,myScore);
                MailManager.sendMail(userId, eMailType.SYSTEM.getValue(), reward, content, title);
                getLogger().error("FlowerStudy dealOfflineExamEventSync sendMail activityId = {},userId = {}",activityInfo.getActivityId(),userId);
            }
        }
    }



}
